function saveMatrices(n,N,dt,rand)
% Given number of zones n (up to 1 implemented currently; working on up to
% 9), given the prediction horizon N (up to 1440 is reasonable), and a
% sampling rate of dt (in units of days, e.g. 1/24/60 for 1 minute), and
% indicate if random load is wanted (rand =1) or if load should be
% consistent (rand=0 gives first n load profiles).
% autogenerate matrices Hp^-1, M, A_i for i = 1,...,n.
% Then, write them to bin files with the name format
% e.g. 'A_n1_N10.bin' generated by the following code
%
% filenameA = ['A_n' num2str(n) '_N' num2str(N) '.bin'];
% fid = fopen(filenameA,'w');
% [mA,nA]= size(A);
% major = [2];
% fwrite(fid, [mA,nA], 'int32');
% fwrite(fid, major, 'int32');
% fwrite(fid, A, 'float32');
% fclose(fid);
% 

close all

% Nitesh wants this silly number
major = 2;

[A,B,d,Hp,M] = makeMatrices(n,N,dt,rand);

%% Write A, B to file
for zone = 1:n
    filename_Ai = ['matrixbin/A_' num2str(zone) '_N' num2str(N) '.bin'];
    fidAi = fopen(filename_Ai,'w');
    [mA,nA] = size(A{zone});
    fwrite(fidAi,[mA,nA],'int32');
    fwrite(fidAi,major,'int32');
    fwrite(fidAi,A{zone},'double');
    fclose(fidAi);
    
    filename_Bi = ['matrixbin/B_' num2str(zone) '_N' num2str(N) '.bin'];
    fidBi = fopen(filename_Bi,'w');
    [mB,nB] = size(B{zone});
    fwrite(fidBi,[mB,nB],'int32');
    fwrite(fidBi,major,'int32');
    fwrite(fidBi,B{zone},'double');
    fclose(fidBi);
end     


%% Write HpINV to file 
HpINV = Hp^-1;
filenameHpINV = ['matrixbin/HpINV_n' num2str(n) '_N' num2str(N) '.bin'];
fidHpINV = fopen(filenameHpINV,'w');
[mHpINV,nHpINV] = size(HpINV);
fwrite(fidHpINV, [mHpINV,nHpINV], 'int32');
fwrite(fidHpINV, major, 'int32');
fwrite(fidHpINV, HpINV, 'double');
fclose(fidHpINV);

%% Write M to file
filenameM = ['matrixbin/M_n' num2str(n) '_N' num2str(N) '.bin'];
fidM = fopen(filenameM,'w');
[mM,nM] = size(M);
fwrite(fidM, [mM,nM], 'int32');
fwrite(fidM, major, 'int32');
fwrite(fidM, M, 'double');
fclose(fidM);


%% Write disturbance
filenamed = ['matrixbin/d_n' num2str(n) '_N' num2str(N) '.bin'];
fidd = fopen(filenamed,'w');
[md,nd] = size(d);
fwrite(fidd, [md,nd], 'int32');
fwrite(fidd, major, 'int32');
fwrite(fidd, d, 'double');
fclose(fidd);
